package com.wanpinghui.supplier.user;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.util.Base64;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.wanpinghui.supplier.R;
import com.wanpinghui.supplier.common.BaseActivity;
import com.wanpinghui.supplier.user.company.CompanyInfoEditActivity;
import com.wanpinghui.supplier.user.company.CompanyNameActivity;
import com.wanpinghui.supplier.widgets.TitlePanelLayoutUser;
import com.wanpinghui.wphlibrary.WPHSdk;
import com.wanpinghui.wphlibrary.common.dialog.LoadingDialog;
import com.wanpinghui.wphlibrary.model.oauth.UserInfoUtil;
import com.wanpinghui.wphlibrary.model.oauth.bean.UserBean;
import com.wanpinghui.wphlibrary.model.oauth.bean.UserInformation;
import com.wanpinghui.wphlibrary.model.user.UserInfoService;
import com.wanpinghui.wphlibrary.model.user.bean.AvaterBean;
import com.wanpinghui.wphlibrary.model.user.bean.CompanyBean;
import com.wanpinghui.wphlibrary.photovideo.bean.UploadFileBean;
import com.wanpinghui.wphlibrary.photovideo.view.ClipActivity;
import com.yunshl.yunshllibrary.utils.DevicesUtil;
import com.yunshl.yunshllibrary.utils.TextUtil;
import com.yunshl.yunshllibrary.view.YunShlEditText;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;

import jp.wasabeef.glide.transformations.CropCircleTransformation;
import me.nereo.multi_image_selector.PhotoPickManager;
import retrofit.callback.YRequestCallback;

/**
 * 功能描述
 * author:caitiangui
 * time:2017/11/27
 */

@ContentView(R.layout.layout_activity_update_userinfo)
public class UpdateUserInfoActivity extends BaseActivity {
    private static final int REQUEST_SELECT_PHOTO = 1;
    private static final int CLIP_PHOTO = 0x12;
    @ViewInject(R.id.tpl_title)
    private TitlePanelLayoutUser mLayoutTitle;

    @ViewInject(R.id.fl_head_bg)
    private FrameLayout mHeadBgFl;

    @ViewInject(R.id.iv_edit_head)
    private ImageView iv_edit_head;

    @ViewInject(R.id.iv_head)
    private ImageView iv_head;

    private String photoPath;

    @ViewInject(R.id.edt_name)
    private YunShlEditText edt_name;

    @ViewInject(R.id.iv_male)
    private ImageView iv_male;

    @ViewInject(R.id.iv_female)
    private ImageView iv_female;

    @ViewInject(R.id.tv_phone)
    private TextView tv_phone;

    @ViewInject(R.id.edt_address)
    private YunShlEditText edt_address;

    @ViewInject(R.id.edt_position_name)
    private YunShlEditText edt_position_name;

    @ViewInject(R.id.iv_company)
    private ImageView iv_company;

    @ViewInject(R.id.iv_person)
    private ImageView iv_person;

    @ViewInject(R.id.line1)
    private View line1;

    @ViewInject(R.id.edt_company_name)
    private YunShlEditText edt_company_name;

    @ViewInject(R.id.rl_share_qrcode)
    private RelativeLayout rl_share_qrcode;

    @ViewInject(R.id.rl_mine_company)
    private RelativeLayout rl_mine_company;

    @ViewInject(R.id.tv_company_name_pos)
    private TextView tv_company_name_pos;

    private UserBean userBeanInfo;
    private UserInformation userBean;
    private ArrayList<UploadFileBean> userList;
    private String com_name;


    @Override
    public String getName() {
        return null;
    }

    @Override
    public boolean isBar() {
        return false;
    }

    @Override
    public void initViews() {
        mLayoutTitle.setRightText("保存");
        mLayoutTitle.showRightText();
        mLayoutTitle.setRightTextColor(ContextCompat.getColor(this,R.color.colorPrimaryBlue));
        edt_name.setType(YunShlEditText.TYPE_ONLY_ZH);
        edt_address.setType(YunShlEditText.CATEGORY_CHARACTER);
        edt_position_name.setType(YunShlEditText.CATEGORY_CHARACTER);
        edt_company_name.setType(YunShlEditText.CATEGORY_CHARACTER);
    }

    @Override
    protected void onResume() {
        super.onResume();
        userBeanInfo = UserInfoUtil.getUserInfo();
        if (userBeanInfo != null && userBeanInfo.getUser() != null) {
            userBean = userBeanInfo.getUser();
            edt_name.setText(userBean.getNickname());
//            edt_address.setText(userBean.getAddr());
//            edt_position_name.setText(userBean.getPos());
//            edt_company_name.setText(changeCom(userBean.getCom()));
            Glide.with(UpdateUserInfoActivity.this).load(userBean.getAvatar()+ "_thumbnail").bitmapTransform(new CropCircleTransformation(UpdateUserInfoActivity.this)).placeholder(R.mipmap.address_list_bg_head).into(iv_head);
            tv_phone.setText(userBean.getMobile());
            if (userBean.isMan()) {
                iv_male.setSelected(true);
                iv_female.setSelected(false);
            } else {
                iv_female.setSelected(true);
                iv_male.setSelected(false);
            }
            com_name = userBean.getCom();
            if (TextUtil.isEmpty(com_name)) {
                tv_company_name_pos.setTextColor(ContextCompat.getColor(this,R.color.colorTextPrimaryHint));
                Drawable drawable = ContextCompat.getDrawable(this,R.mipmap.address_list_friend_warn);
                drawable.setBounds(0, 0, 40, 40);
                tv_company_name_pos.setCompoundDrawablePadding(DevicesUtil.dip2px(this,5f));
                tv_company_name_pos.setCompoundDrawables(drawable,null,null,null);
                tv_company_name_pos.setText("编辑您的公司信息/职称");
//                iv_company.setSelected(false);
//                iv_person.setSelected(true);
//                edt_company_name.setVisibility(View.GONE);
//                line1.setVisibility(View.GONE);
            } else {
                tv_company_name_pos.setTextColor(ContextCompat.getColor(this,R.color.colorTextPrimaryOne));
                tv_company_name_pos.setCompoundDrawables(null,null,null,null);
                if (TextUtil.isNotEmpty(userBean.getPos())) {
                    tv_company_name_pos.setText(userBean.getCom()+ "/" + userBean.getPos());
                } else {
                    tv_company_name_pos.setText(userBean.getCom()+ "/暂无");
                }
//                iv_company.setSelected(true);
//                iv_person.setSelected(false);
            }
        }
    }

    @Override
    public void bindEvents() {
        mLayoutTitle.setOnClickBacktrack(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mLayoutTitle.setOnClickRightTxt(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                UserInformation bean = new UserInformation();
                int gender;
                if (iv_male.isSelected()) {
                    gender = 1;
                } else {
                    gender = 0;
                }
                bean.setGender(gender);
                bean.setNickname(edt_name.getTextString());
//                if (iv_company.isSelected()) {
//                    if (edt_company_name.getTextString().isEmpty()) {
//                        showWarningText("请输入公司名");
//                        return;
//                    }
//                    bean.setCom(edt_company_name.getTextString());
//                } else {
//                    bean.setCom("");
//                }
//                bean.setAddr(edt_address.getTextString());
//                bean.setPos(edt_position_name.getTextString());

                WPHSdk.getService(UserInfoService.class)
                        .UpdateUserInfo(bean, new YRequestCallback<UserInformation>() {
                            @Override
                            public void onSuccess(UserInformation var1) {
                                //showWarningText("保存成功");
                                finish();
                            }

                            @Override
                            public void onFailed(int var1, String message) {
                                showWarningText(message);
                            }

                            @Override
                            public void onException(Throwable var1) {
                                var1.printStackTrace();
                            }
                        });

            }
        });
        iv_edit_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PhotoPickManager.selectPic(UpdateUserInfoActivity.this, REQUEST_SELECT_PHOTO, 1, false, 0);
            }
        });
        iv_female.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iv_female.setSelected(true);
                iv_male.setSelected(false);
            }
        });
        iv_male.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iv_male.setSelected(true);
                iv_female.setSelected(false);
            }
        });
        iv_company.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iv_company.setSelected(true);
                iv_person.setSelected(false);
                edt_company_name.setVisibility(View.VISIBLE);
                line1.setVisibility(View.VISIBLE);
            }
        });
        iv_person.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iv_company.setSelected(false);
                iv_person.setSelected(true);
                edt_company_name.setVisibility(View.GONE);
                line1.setVisibility(View.GONE);
            }
        });
        rl_share_qrcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(UpdateUserInfoActivity.this, QRcodeCardActivity.class));
            }
        });
        rl_mine_company.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                WPHSdk.getService(UserInfoService.class)
                        .getMyCompany(new YRequestCallback<CompanyBean>() {
                            @Override
                            public void onSuccess(CompanyBean var1) {
                                if (var1 != null) {

                                    if ( var1 .getId() <1 && var1.getAudit_status() <11) {
                                        Intent intent = new Intent(UpdateUserInfoActivity.this, CompanyNameActivity.class);
                                        if (var1 .getAudit_status() == 1){
                                            intent.putExtra("edit", true);
                                        }
                                        intent.putExtra("bean",var1);
                                        startActivity(intent);
                                    } else {
                                        Intent intent = new Intent(UpdateUserInfoActivity.this, CompanyInfoEditActivity.class);
                                        intent.putExtra("bean",var1);
                                        startActivity(intent);
                                    }

                                }
                            }

                            @Override
                            public void onFailed(int var1, String message) {
                                showWarningText(message);
                            }

                            @Override
                            public void onException(Throwable var1) {

                            }
                        });
            }
        });
    }

    @Override
    public void initData() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        List<String> photoList = PhotoPickManager.getPhoto(data);
//        if (photoList != null && photoList.size() > 0) {
//             photoPath = photoList.get(0);
//            Glide.with(UpdateUserInfoActivity.this).load(photoPath).asBitmap().into(iv_head);
//        }
        if (requestCode == REQUEST_SELECT_PHOTO) {
            if (data != null) {
                Intent intent = new Intent(UpdateUserInfoActivity.this, ClipActivity.class);
                intent.putExtra("data", PhotoPickManager.getPhoto(data));
                //   intent.putExtra("scale",2);
                startActivityForResult(intent, CLIP_PHOTO);
            }
        } else if (requestCode == CLIP_PHOTO) {
            if (data != null) {
                LoadingDialog.Build(this).setContent("正在上传").show();
                ArrayList list = data.getParcelableArrayListExtra("result");
                userList = new ArrayList<>();
                userList.addAll(list);
                final String paths = userList.get(0).getPath();
                Bitmap bitmap = BitmapFactory.decodeFile(paths);
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 80, stream);
                byte[] bytes = stream.toByteArray();
                WPHSdk.getService(UserInfoService.class).avatar(Base64.encodeToString(bytes, Base64.DEFAULT), new YRequestCallback<AvaterBean>() {
                    @Override
                    public void onSuccess(AvaterBean var1) {
                        showWarningText("保存成功");
                        LoadingDialog.dismissDialog();
                        userBean.setAvatar(var1.getImg());
                        userBeanInfo.setUser(userBean);
                        UserInfoUtil.saveUserInfo(userBeanInfo);
                        Glide.with(UpdateUserInfoActivity.this).load(userBean.getAvatar()+ "_thumbnail").bitmapTransform(new CropCircleTransformation(UpdateUserInfoActivity.this)).placeholder(R.mipmap.address_list_bg_head).into(iv_head);
                        //Glide.with(UpdateUserInfoActivity.this).load(userBean.getAddr()+"_thumbnail").bitmapTransform(new CropCircleTransformation(UpdateUserInfoActivity.this)).into(iv_head);
                    }

                    @Override
                    public void onFailed(int var1, String message) {
                        showWarningText(message);
                        LoadingDialog.dismissDialog();
                    }

                    @Override
                    public void onException(Throwable var1) {
                        showWarningText(var1.getMessage());
                        LoadingDialog.dismissDialog();
                    }
                });
                //  upDataImg();
            }

        }
    }

//    公司名称长度超过20个字，只显示20个字后面显示...
    private String changeCom(String companyName){
        if(companyName.length() > 20){
            return companyName.substring(0, 19)+"...";
        }else{
            return companyName;
        }
    }

}
